#!/bin/bash

# 指定要检查的文件路径
file_path=".env"

# 使用条件语句检查文件是否存在
if [ -e "$file_path" ]; then
  echo "初始配置文件已存在：$file_path"
  
  # 提示用户是否覆盖文件
  read -p "是否要重新生成配置文件？(y/n, 默认n): " choice

  # 如果用户选择不覆盖，则退出
  if [ "$choice" != "y" ]; then
    exit 1
  fi
fi

mysql_password=$(openssl rand -base64 12 | tr -d '+/' | head -c 12)
redis_password=$(openssl rand -base64 12 | tr -d '+/' | head -c 12)
jwt_secret=$(openssl rand -base64 12 | tr -d '+/' | head -c 12)

cat <<EOT > .env
MYSQL_ROOT_PASSWORD=$mysql_password
REDIS_PASSWORD=$redis_password
JWT_SECRET=$jwt_secret
EOT

cat <<EOT > conf/redis.conf
requirepass $redis_password
slaveof no one
EOT

read -p "是否安装前置nginx？(y/n, 默认y): " with_nginx
rm -rf docker-compose.yml
if [ "$with_nginx" != "n" ]; then
  read -p "请输入nginx http端口号（默认: 80）: " http_port
  read -p "请输入nginx https端口号（默认: 443）: " https_port
  read -p "请输入nginx 绑定域名（默认: _）: " binding_doman
  http_port=${http_port:-80}
  https_port=${https_port:-443}
  binding_domain=${binding_doman:-_}

  rm -rf conf/nginx.conf
  cp conf/nginx.conf.tmpl conf/nginx.conf
  sed -i 's/http_port/'$http_port'/g' conf/nginx.conf
  sed -i 's/https_port/'$https_port'/g' conf/nginx.conf
  sed -i 's/binding_domain/'$binding_domain'/g' conf/nginx.conf
  openssl req -x509 -nodes -newkey rsa:2048 -keyout conf/certs/tls.key -out conf/certs/tls.crt -days 3650 -subj "/C=US/ST=State/L=Locality/O=Organization/OU=Organizational Unit/CN=Common Name/emailAddress=Email Address"

  cp docker-compose-with-nginx.yml.tmpl docker-compose.yml
else
  cp docker-compose.yml.tmpl docker-compose.yml
fi
